package hservice

import (
	"encoding/json"
	"io/ioutil"

	"advertoper/errorcode"

	log "github.com/cihub/seelog"
)

var (
	defaultRouterTableService *RouterTableService
)

type RouterTableService struct {
}

func GetRouterTableService() *RouterTableService {
	if defaultRouterTableService == nil {
		defaultRouterTableService = &RouterTableService{}
	}
	return defaultRouterTableService
}

const (
	iosRouterTable          = "../conf/ios_router_table.json"
	androidRouterTable      = "../conf/android_router_table.json"
	androidOnLineParameters = "../conf/android_online_parameters.json"
)

//获取路由表
func (p *RouterTableService) GetRouterTable(plat, v int) (uint, string, map[string]interface{}) {
	filename := ""
	if plat == 2 {
		filename = iosRouterTable
		if v == 2 {
			filename = "../conf/ios_router_table_v2.json"
		}
	} else {
		filename = androidRouterTable
	}
	data, err := p.readFile(filename)
	if err != nil {
		return 1002, err.Error(), nil
	}
	return errorcode.EC_GL_SUCCESS, errorcode.Msg(errorcode.EC_GL_SUCCESS), data

}

func (p *RouterTableService) readFile(filename string) (map[string]interface{}, error) {
	bytes, err := ioutil.ReadFile(filename)
	if err != nil {
		log.Errorf("ReadFile fail ,readFile~ , err is %s ", err.Error())
		return nil, err
	}
	data := make(map[string]interface{})
	if err2 := json.Unmarshal(bytes, &data); err2 != nil {
		log.Errorf("json uumarshal fail ,readFile~ , err is %s ", err2.Error())
		return nil, err2
	}
	return data, nil
}

//获取客户端在线参数
func (p *RouterTableService) GetOnLineParameters(plat int) (uint, string, map[string]interface{}) {
	filename := ""
	if plat == 2 { //这里ios没有此功能
		filename = androidOnLineParameters
	} else {
		filename = androidOnLineParameters
	}
	data, err := p.readFile(filename)
	if err != nil {
		return 1002, err.Error(), nil
	}
	return errorcode.EC_GL_SUCCESS, errorcode.Msg(errorcode.EC_GL_SUCCESS), data
}
